package com.br.aiops.receiver.es.query;

import lombok.Builder;
import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@Data
@Builder
public class Result {

    private static final Logger LOGGER = LoggerFactory.getLogger(Result.class);

    public static final String COMPUTE_TYPE_COUNT = "count";
    public static final String COMPUTE_TYPE_MAX = "max";
    public static final String COMPUTE_TYPE_MIN = "min";
    public static final String COMPUTE_TYPE_AVG = "avg";
    public static final String COMPUTE_TYPE_SUM = "sum";

    private long totalCount;
    private List<Record> records;
    private Set<String> hosts;
    private String message;

    public long totalCount() {
        return this.totalCount;
    }

    public ResultFilter compute(String groupField) {
        Map<Object, Object> groupBy = records.stream().collect(Collectors.groupingByConcurrent(record -> record.getFields().getOrDefault(groupField, "defaultValue")))
                .entrySet().stream()
                .collect(Collectors.toMap(Map.Entry::getKey, entry -> computeByType(entry.getValue())));
        return ResultFilter.builder().result(groupBy).build();
    }

    private double computeByType(List<Record> records) {
        return count(records);
    }

    public long count(List<Record> records) {
        return records.size();
    }
}
